﻿using System;
using System.Drawing;
using TimedText.Styling;
using TimedTextLibrary;

namespace Microsoft.Office.PowerPoint.STAMP.Core
{
    internal static class CaptionStyleParser
    {
        private static readonly CaptionStyle _defaultStyle = new CaptionStyle();

        internal static CaptionStyle ToCaptionStyle(TimedTextCaption caption)
        {
            var style = new CaptionStyle
                            {
                                FontColor = caption.FontColor.HasValue ? caption.FontColor.Value : _defaultStyle.FontColor,
                                BackgroundColor = caption.BackgroundColor.HasValue ? caption.BackgroundColor.Value : _defaultStyle.BackgroundColor
                            };

            if (style.BackgroundColor == Color.Transparent)
            {
                style.BackgroundColor = Properties.Settings.Default.DefaultBackgroundColor;
                if (style.FontColor == Color.Black)
                {
                    style.FontColor = Properties.Settings.Default.DefaultFontColor;
                }
            }

            if (caption.FontSize != null)
            {
                style.FontSize = new Length
                                     {
                                         Unit = ConvertEnum<Unit, LengthUnit>(caption.FontSize.UnitMeasureHorizontal),
                                         Value = (float)caption.FontSize.First
                                     };
            }

            style.FontStyle = caption.FontStyle.HasValue ? caption.FontStyle.Value : _defaultStyle.FontStyle;
            style.FontStyle |= caption.FontWeight.HasValue ? caption.FontWeight.Value : style.FontStyle;
            
            TextDecorationAttributeValue parsedDecorationAttributeValue;
            if (Enum.TryParse(caption.TextDecoration, true, out parsedDecorationAttributeValue) &&
                parsedDecorationAttributeValue == TextDecorationAttributeValue.underline)
                style.FontStyle |= FontStyle.Underline;


            TextAlignAttibuteValue parsedTextAlign;
            style.TextAlignStyleProperty = caption.TextAlign.EnumTryParse(true, out parsedTextAlign)
                                               ? parsedTextAlign
                                               : _defaultStyle.TextAlignStyleProperty;


            return style;
        }

        private static TResult ConvertEnum<TSource, TResult>(TSource source)
            where TSource : struct
            where TResult : struct
        {
            TResult result;
            return source.ToString().EnumTryParse(true, out result)
                       ? result
                       : default(TResult);
        }
    }
}